/*
 * Copyright (C) 2009 Rafael Fernandes
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.phonebooksharing.android.async;

import java.io.Serializable;

import android.app.Activity;
import android.app.ProgressDialog;
import android.widget.Toast;

import com.phonebooksharing.android.util.NetworkHandlerTask;
import com.phonebooksharing.dto.ReturnItem;

public class SendTextMessageTask extends NetworkHandlerTask<Void, Void, Boolean> {
    private ProgressDialog progress;
    private Activity cx;
    private String url;
    private Serializable serializable;
    private boolean shallClose;
    
    public SendTextMessageTask(Activity cx, String url, Serializable serializable) {
        this(cx, url, serializable, true);
    }
    
    public SendTextMessageTask(Activity cx, String url, Serializable serializable, boolean shallClose) {
        this.cx = cx;
        this.url = url;
        this.serializable = serializable;
        this.shallClose = shallClose;
    }
    
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        
        progress = new ProgressDialog(cx);
        progress.setTitle("Processing");
        progress.setMessage("Please wait while we post your message online...");
        progress.setIndeterminate(true);
        progress.setCancelable(false);
        progress.show();
    }

    @Override
    protected Boolean doInBackground(Void... texts) {
        
        boolean isOK = false;
        try {
            ReturnItem ri = (ReturnItem)doNetworkPost(url, serializable);
            isOK = ri.isOK();
        } catch (Exception e) {
            e.printStackTrace();
            isOK = false;
        }
        
        return isOK;
    }
    
    @Override
    protected void onPostExecute(Boolean result) {
        super.onPostExecute(result);
        progress.dismiss();
        if(result) {
            Toast.makeText(cx, "Your text message has been send successfully!", Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(cx, "It was not possible to deliver your message online, we'll do it on next sync.", Toast.LENGTH_LONG).show();
        }
        if(shallClose) cx.finish();
    }
}